'use strict'

const Koa = require('koa');
const cors = require('koa-cors');
const bodyParser = require('koa-bodyparser');
const router = require('koa-router')();

const {
    Sequelize,
    Op,
    DataTypes
} = require('sequelize');
const {
    body
} = require('koa/lib/response');

const port = 5600;

let app = new Koa();

// 链接数据库
const sequelize = new Sequelize('Blogs', 'sa', '123456', {
    host: 'localhost',
    dialect: 'mssql'
});

// 创建分类表
let Category = sequelize.define('Category', {
    cate_name: {
        type: DataTypes.STRING,
        allowNull: true
    }
})

// 创建博客数据表
let Blog = sequelize.define('Blog', {
    title: {
        type: DataTypes.STRING,
        allowNull: false,
    },
    abstract: {
        type: DataTypes.STRING,
        allowNull: false
    },
    body: {
        type: DataTypes.STRING,
        allowNull: false
    },
    cateId: {
        type: DataTypes.INTEGER,
        allowNull: false
    },
    author: {
        type: DataTypes.STRING,
        allowNull: false
    }
});

// 初始化数据
// init();

// 请求分类数据
router.get('/category',async (ctx)=>{
    let list=await Category.findAll({
        order:['id']
    })
    ctx.body={
        code: 1000,
        msg: '获取数据成功',
        data: list
    };
})

// 请求博客数据
router.get('/blog', async (ctx) => {
    // 获得前端传回的分页参数，pageIndex是指获取第几页的数据，pageSize是指页的记录数，默认第 1 页每页 12 条数据
    let pageIndex = ctx.request.query.pageIndex || 1;
    let pageSize = ctx.request.query.pageSize || 12;

    let keyword = ctx.request.query.keyword || '';
    let cate = await Category.findAll();

    // 判断 keyword 如果有则 返回查询后的数据 ，无则返回指定页面的数据默认第一页。
    if (keyword) {
        console.log(keyword);
        let {
            rows,
            count
        } = await Blog.findAndCountAll({
            offset: (pageIndex - 1) * pageSize,
            limit: pageSize,
            where: {
                [Op.or]: [{
                        title: {
                            [Op.like]: `%${keyword}%`
                        }
                    },
                    {
                        abstract: {
                            [Op.like]: `%${keyword}%`
                        }
                    },
                    {
                        body: {
                            [Op.like]: `%${keyword}%`
                        }
                    },
                    {
                        author: {
                            [Op.like]: `%${keyword}%`
                        }
                    }
                ]
            },
            order: ['id']
        });
        rows.forEach(item => {
            let tmpCate = cate.find(x => {
                return x.id === item.cateId
            })
            if (tmpCate) {
                item.dataValues.CategoryName = tmpCate.cate_name
            }
        })
        ctx.body = {
            code: 1000,
            msg: '获取数据成功',
            data: {
                pageIndex,
                pageSize,
                totalCount: count,
                rows
            }
        };
    } else {
        let {
            rows,
            count
        } = await Blog.findAndCountAll({
            offset: (pageIndex - 1) * pageSize,
            limit: pageSize,
            order: ['id']
        });
        // console.log(rows);
        rows.forEach(item => {
            let tmpCate = cate.find(x => {
                return x.id === item.cateId
            })
            if (tmpCate) {
                item.dataValues.CategoryName = tmpCate.cate_name
            }
        })
        ctx.body = {
            code: 1000,
            msg: '获取数据成功',
            data: {
                pageIndex,
                pageSize,
                totalCount: count,
                rows
            }
        };
    }

})

// 请求指定 id 数据
router.get('/blog/:id',async (ctx)=>{
    let id=ctx.request.params.id
    let list=await Blog.findByPk(id)
    if (list) {
        ctx.body={
            code: 1000,
            msg: '获取数据成功',
            data: list
        };
    }else{
        ctx.body={
            code: 400,
            msg: '获取数据失败',
            data: list
        };
    }
})

// 新增博客数据
router.post('/blog', async (ctx) => {
    let tmpObj = ctx.request.body
    let entity = Blog.create(tmpObj);
    ctx.body = {
        code: 1000,
        msg: '新增数据成功',
        data: entity
    }
})

// 更新博客数据
router.put('/blog/:id', async (ctx) => {
    let id = ctx.request.params.id;
    let tmpObj = ctx.request.body
    let list = await Blog.findByPk(id)
    if (list) {
        let entity = Blog.update(tmpObj, {
            where: {
                id: id
            }
        });
        ctx.body = {
            code: 1000,
            msg: '更新数据成功',
            data: entity
        }
    } else {
        ctx.body = {
            code: 400,
            msg: '查无此数据',
            data: null
        }
    }
})

// 删除博客数据
router.delete('/blog/:id', async (ctx) => {
    let id = ctx.request.params.id;
    let list = await Blog.findByPk(id)
    if (list) {
        Blog.destroy({
            where: {
                id: id
            }
        });
        ctx.body = {
            code: 1000,
            msg: '删除数据成功',
            data: null
        }
    }else{
        ctx.body = {
            code: 400,
            msg: '查无此数据',
            data: null
        }
    }
})

// 引入跨域中间件
app.use(cors())
// 引入解析post、put请求时body中的数据中间件
app.use(bodyParser())
// 引入路由中间件
app.use(router.routes())

app.listen(port, () => {
    console.log(`http://localhost:${port}`);
})


function init() {
    sequelize.sync({
        force: true
    }).then(async () => {
        let cate = await Category.bulkCreate([{
                cate_name: '.Net'
            },
            {
                cate_name: '编程技术'
            },
            {
                cate_name: '服务器'
            },
            {
                cate_name: 'Linux'
            },
            {
                cate_name: '大数据'
            }
        ]);
        Blog.bulkCreate([{
                title: '论EF Croe的自我修养',
                abstract: '论EF Croe的自我修养',
                body: '论EF Croe的自我修养',
                classify: '.Net',
                author: 'InCerry',
                cateId: cate[0].id
            },
            {
                title: 'DDD之我见',
                abstract: 'DDD之我见',
                body: 'DDD之我见',
                classify: '编程技术',
                author: '某大神',
                cateId: cate[1].id
            },
            {
                title: 'nginx负载平衡的几种策略',
                abstract: 'nginx负载平衡的几种策略',
                body: 'nginx负载平衡的几种策略',
                classify: '服务器',
                author: '老胡来也',
                cateId: cate[2].id
            },
            {
                title: 'Liunx用户创建的学习研究',
                abstract: 'Liunx用户创建的学习研究',
                body: 'Liunx用户创建的学习研究',
                classify: 'Liunx',
                author: '某大神',
                cateId: cate[3].id
            },
            {
                title: '大数据仪表盘探讨',
                abstract: '大数据仪表盘探讨',
                body: '大数据仪表盘探讨',
                classify: '大数据',
                author: '居家博士',
                cateId: cate[4].id
            }
        ]);
    })
}